package com.cms.entity;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.annotation.JSONField;
import com.cms.entity.base.BaseProduct;
import com.cms.util.DBUtils;
import com.jfinal.core.JFinal;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;

/**
 * Entity - 商品
 * 
 * 
 * 
 */
@SuppressWarnings("serial")
public class Product extends BaseProduct<Product> {

    /**
     * 商品类型
     */
    public enum Type{
        SELL("出售中"),
        SELL_OUT("已售馨"),
        OFF_SHELF("下架中");
        public String text;
        Type(String text){
            this.text = text;
        }
        public String getText(){
            return this.text;
        }
    }
	
    /**
     * 
     */
    @JSONField(serialize=false)  
    private GroupProduct groupProduct;

    /**
     * 获取
     * 
     * @return 
     */
    public GroupProduct getGroupProduct(){
        if(groupProduct == null){
        	groupProduct =  new GroupProduct().dao().findByProductId(getId());
        }
        return groupProduct;
    }
    
    /**
     * 
     */
    @JSONField(serialize=false)  
    private SeckillProduct seckillProduct;

    /**
     * 获取
     * 
     * @return 
     */
    public SeckillProduct getSeckillProduct(){
        if(seckillProduct == null){
        	seckillProduct =  new SeckillProduct().dao().findByProductId(getId());
        }
        return seckillProduct;
    }

    /**
     * 是否是秒杀
     *
     * @return
     */
    public Boolean getIsSeckill(){
        if(getSeckillProduct()!=null){
            return seckillProduct.getSeckill().getIsStart();
        }
        return false;
    }

    /**
     * 是否是拼团
     *
     * @return
     */
    public Boolean getIsGroup(){
        if(getGroupProduct()!=null){
            return groupProduct.getGroup().getIsStart();
        }
        return false;
    }
	
    /**
     * 品牌
     */
    @JSONField(serialize=false)  
    private Brand brand;

    /**
     * 获取品牌
     * 
     * @return 品牌
     */
    public Brand getBrand(){
        if(brand == null){
        	brand =  new Brand().dao().findById(getBrandId());
        }
        return brand;
    }
    
    /**
     * 商品分类
     */
    private ProductCategory productCategory;
    
   /**
     * 查找商品分页
     * 
     * @param pageNumber
     *            页码
     * @param pageSize
     *            每页记录数
     * @param productCategoryId
     *            商品分类Id
     * @return 商品分页
     */
    public Page<Product> findPage(Integer pageNumber,Integer pageSize,Long productCategoryId,String name,Product.Type type,Long brandId){
        String filterSql = "";
        if(productCategoryId!=null){
            filterSql+=" and productCategoryId="+productCategoryId;
        }
        if(StrKit.notBlank(name)){
            filterSql+=" and name like '%"+name+"%'";
        }
        if(type!=null){
        	if(type.ordinal() == Product.Type.SELL.ordinal()){
        		filterSql+=" and isMarketable=1";
        	}else if(type.ordinal() == Product.Type.SELL_OUT.ordinal()){
        		filterSql+=" and stock<=0";
        	}else if(type.ordinal() == Product.Type.OFF_SHELF.ordinal()){
        		filterSql+=" and isMarketable=0";
        	}
        }
        if(brandId!=null){
        	filterSql+=" and brandId="+brandId;
        }
        String orderBySql = DBUtils.getOrderBySql("createDate desc");
        return paginate(pageNumber, pageSize, "select *", "from cms_product where 1=1 "+filterSql+orderBySql);
    }
    
    /**
     * 查找商品分页
     * 
     * @param pageNumber
     *            页码
     * @param pageSize
     *            每页记录数
     * @param productCategoryId
     *            商品分类Id
     * @param keyword
     *            关键词
     * @param orderBy
     *            排序
     * @return 商品分页
     */
    public Page<Product> findPage(Integer pageNumber,Integer pageSize,Long productCategoryId,Long brandId,Boolean isMarketable,String keyword,String tag,String orderBy){
        String filterSql = "";
        if(productCategoryId!=null){
		    filterSql+=" and (productCategoryId="+productCategoryId+" or productCategoryId in ( select id from cms_product_category where treePath  like '%"+ProductCategory.TREE_PATH_SEPARATOR+productCategoryId+ProductCategory.TREE_PATH_SEPARATOR+"%'))";
		}
        if(brandId!=null){
        	filterSql+=" and brandId="+brandId;
        }
        if(isMarketable!=null){
        	filterSql+=" and isMarketable="+isMarketable;
        }
        if(StrKit.notBlank(keyword)){
            filterSql+=" and name like '%"+keyword+"%'";
        }
        if(StrKit.notBlank(tag)){
            filterSql+=" and tag like '%"+tag+"%'";
        }
        String orderBySql = "";
        if(StringUtils.isBlank(orderBy)){
            orderBySql = DBUtils.getOrderBySql("sort desc,createDate desc");
        }else{
        	if("price".equals(orderBy)){
        		orderBySql = "price desc";
    		}else if("sales".equals(orderBy)){
    			orderBySql = "sales desc";
    		}
            orderBySql = DBUtils.getOrderBySql(orderBy);
        }
        return paginate(pageNumber, pageSize, "select *", "from cms_product where 1=1 "+filterSql+orderBySql);
    }
    
    /**
     * 查找商品列表
     * 
     * @param productCategoryId
     *            商品分类Id
     * @param first
     *            起始记录
     * @param count
     *            数量
     * @param orderBy
     *            排序
     * @return 商品列表
     */
    public List<Product> findList(Long productCategoryId,String tag,Boolean isMarketable,Integer first,Integer count,String condition,String orderBy){
        String filterSql = "";
        if(productCategoryId!=null){
		    filterSql+=" and (productCategoryId="+productCategoryId+" or productCategoryId in ( select id from cms_product_category where treePath  like '%"+ProductCategory.TREE_PATH_SEPARATOR+productCategoryId+ProductCategory.TREE_PATH_SEPARATOR+"%'))";
		}
        if(StringUtils.isNotBlank(tag)){
        	filterSql+=" and tag like '%"+tag+"%'";
        }
        if(isMarketable!=null){
        	filterSql+=" and isMarketable="+isMarketable;
        }
        String orderBySql = "";
        if(StringUtils.isBlank(orderBy)){
            orderBySql = DBUtils.getOrderBySql("sort desc,createDate desc");
        }else{
            orderBySql = DBUtils.getOrderBySql(orderBy);
        }
        if(StringUtils.isNotBlank(condition)){
        	filterSql+=" and "+condition;
        }
        String countSql=DBUtils.getCountSql(first, count);
        return find("select * from cms_product where 1=1 "+filterSql+orderBySql+countSql);
    }
    
    /**
     * 获取商品分类
     * @return 商品分类
     */
    public ProductCategory getProductCategory(){
        if(productCategory == null){
            productCategory = new ProductCategory().dao().findById(getProductCategoryId());
        }
        return productCategory;
    }
    
    /**
     * 获取商品图片
     * 
     * @return 商品图片
     */
    /**
     * 获取商品图片
     * 
     * @return 商品图片
     */
    public List<String> getProductImages() {
        if(StrKit.notBlank(getProductImage())){
            return JSONArray.parseArray(getProductImage(), String.class);
        }
        return new ArrayList<>();
    }
    
    public Integer getReviewCount(){
    	return Db.queryInt("select count(*) from cms_product_review where productId=?",getId());
    }
    
    /**
     * 获取路径
     * 
     * @return 路径
     */
    public String getPath() {
        return JFinal.me().getContextPath()+"/product/detail/"+getId();
    }

    /**
     * 获取真实价格
     *
     * @return
     */
    public BigDecimal getRealPrice() {
    	SeckillProduct seckillProduct = new SeckillProduct().findByProductId(getId());
    	if(seckillProduct!=null){
    		Seckill seckill = seckillProduct.getSeckill();
    		if(seckill.getIsStart()){
    			return seckillProduct.getPrice();
    		}
    	}
    	GroupProduct groupProduct = new GroupProduct().findByProductId(getId());
    	if(groupProduct!=null){
    		Group group = groupProduct.getGroup();
    		if(group.getIsStart()){
    			return groupProduct.getPrice();
    		}
    	}
    	return getPrice();
	}

    /**
     * 查找收藏列表
     *
     * @param memberId
     * @return
     */
	public List<Product> findFavList(Long memberId){
		return find("select cp.* from cms_product_fav cpf inner join cms_product cp on cpf.productId=cp.id where memberId=?",memberId);
	}

    /**
     * 查找收藏分页
     *
     * @param pageNumber
     * @param pageSize
     * @param memberId
     * @return
     */
   public Page<Product> findFavPage(Integer pageNumber,Integer pageSize,Long memberId){
        return paginate(pageNumber, pageSize, "select cp.*", "from cms_product_fav cpf inner join cms_product cp on cpf.productId=cp.id where memberId="+memberId+" order by cpf.createDate desc ");
    }
}
